<?php

namespace api\modules\v1\models;

use Yii;
use api\common\models\Common;
use yii\web\NotFoundHttpException;
use yii\web\HttpException;
use api\common\controllers\CommonController;
class Third extends Common
{

    public $type='';
    public $openid='';

    /**
     * @return array|string
     */
    public static function tableName()
    {
        return '{{%user_app}}';
    }

    public function rules()
    {
        return [
            ['type', 'required','message'=>'第三方登录方式不能为空', 'on' => ['bind']],

            ['openid', 'required','message'=>'第三方登录ID不能为空', 'on' => ['bind']],

            ['type', 'in', 'range' => ['qq','wx','wb'], 'on' => ['bind','unbind']],
        ];
    }

    /*
     * 绑定
     */
    public function Bind(){
        if ($this->validate()) {
            $openid_field = $this->type.'_openid';

            if(self::find()->where("$openid_field='".$this->openid."' and phone !='".$this->phone."'")->one()){ //判断该Openid 是否已经存在绑定其他账号
                throw new HttpException(401,'该'.$this->type.'已绑定其他账号',0);
            }

            if($this->$openid_field != ''){
                $this->addError($this->$openid_field, '该账号'.Common::formatType($this->type).'绑定已经存在');
                return false;
            }
            $this->$openid_field = $this->openid;
            if ($this->save(false)) {
                return true;
            }
        }
        return null;
    }


    /*
     * 解绑
     */
    public function Unbind(){
        if ($this->validate()) {
            $openid_field = $this->type.'_openid';
            if($this->$openid_field == ''){
                $this->addError($this->$openid_field, $this->type.'您并未绑定该账号');
                return false;
            }
            $this->$openid_field = '';
            if ($this->save(false)) {
                return true;
            }
        }
        return null;
    }
}
